﻿using Mapster;
using MapsterMapper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using WorkFlowCore.WorkTasks;

namespace WorkFlowCore.Workflows
{
    public static class WorkflowVersionExtension
    {
        private static readonly TypeAdapterConfig _config = new TypeAdapterConfig();
        static WorkflowVersionExtension()
        {
            _config.ForType<WorkflowVersionInfo, WorkflowVersion>()
                .Map(dest => dest.NodeMaps, src => JsonConvert.DeserializeObject<List<NodeMap>>(src.NodeMaps??""))
                .Map(dest => dest.AllNodes, src => JsonConvert.DeserializeObject<List<WorkflowNode>>(src.AllNodes??""));

            _config.ForType<WorkflowVersion, WorkflowVersionInfo>()
                .Map(dest => dest.NodeMaps, src => JsonConvert.SerializeObject(src.NodeMaps ??new List<NodeMap>() ))
                .Map(dest => dest.AllNodes, src => JsonConvert.SerializeObject(src.AllNodes ?? new List<WorkflowNode>()));

        }
        public static WorkflowVersion ToWorkflowVersion(this WorkflowVersionInfo workflowVersionInfo)
        {
            if(workflowVersionInfo==null)
                return new WorkflowVersion();

            var mapper = new Mapper(_config);
            return mapper.Map<WorkflowVersion>(workflowVersionInfo);
        }

        public static WorkflowVersionInfo ToWorkflowVersionInfo(this WorkflowVersion workflowVersion, WorkflowVersionInfo workflowVersionInfo=null)
        {
            if(workflowVersionInfo==null)
                workflowVersionInfo = new WorkflowVersionInfo();

            var mapper = new Mapper(_config);
            return mapper.Map(workflowVersion, workflowVersionInfo);
        }
    }
}
